<?php

namespace app\admin\controller;

use think\Db;
use think\Cache;
use think\Request;

class Pageants extends Common
{
    public function config()
    {
        $where = ['delete_time'=>0];

        $search_name = input('param.search_name');
        if ($search_name) {
            $where['name'] = ['like', '%' . $search_name . '%'];
        }

        $current_id = Db::name('act_pageants_config')
            ->where(['delete_time' => 0])
            ->where('enroll_time', '<= time', time())
            ->where('end_time', '>= time', time())
            ->value('id');
        $this->assign('current_id', $current_id);
        
        $data = Db::name('act_pageants_config')
            ->where($where)
            ->order('id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()])
            ->each(function($item){
                return $item;
            });
        
        $page = $data->render();
        $this->assign('search_name', $search_name);
        $this->assign('data', $data);
        $this->assign('page', $page);
        
        return $this->fetch();
    }
    public function configadd()
    {
        $id = input("id/d", 0);

        if (request()->isAjax()) {
            $post = input('post.');

            $post['description'] = Request::instance()->post('description','','htmlspecialchars');
            $post['description'] = in_content($post['description']);
            if (!$post['name']) return ['err'=>'请输入名称'];
            if (!$post['description']) return ['err'=>'请输入说明内容'];
            if (!$post['enroll_time']) return ['err'=>'请选择报名开始时间'];
            if (!$post['start_time']) return ['err'=>'请选择打分开始时间'];
            if (!$post['end_time']) return ['err'=>'请选择打分结束时间'];

            if (strtotime($post['end_time']) > strtotime($post['start_time']) && strtotime($post['start_time']) >= strtotime($post['enroll_time'])) {
                // 检查时间区间是否重叠
                $last = Db::table('act_pageants_config')
                ->where(['delete_time'=>0, 'id'=>['<>', $id]])
                ->where('(end_time>="'.$post['end_time'].'" and start_time<="'.$post['end_time'] . '") or (start_time<="'.$post['start_time'].'" and end_time>"'.$post['start_time'].'") or (start_time>"'.$post['start_time'].'" and end_time<"'.$post['end_time'].'")')
                            ->find();

                if ($last) return ['err'=>'时间与旧数据(id: '.$last['id'].')冲突'];
            } else {
                return ['err'=>'时间选择错误'];
            }

            if (!$id) {
                $post['create_time'] = time();
                $res = Db::name('act_pageants_config')->insert($post);
                if ($res) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else {
                $post['update_time'] = time();
                $res = Db::name('act_pageants_config')->where('id', $id)->update($post);
                if ($res) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
    
        } else {
            if ($id) {
                $name = Db::name('act_pageants_config')->find($id);

                if ($name) {
                    $this->assign('name', $name);
                } else {
                    return ['err' => 'id参数错误'];
                }
            }
            $data = $this->fetch();
        }

        return $data;
    }
    public function configdel()
    {
        if (request()->isAjax()) {
            $id = input('id');
            if ($id) {
                $db = Db::name('act_pageants_config')->where(['id'=>$id])->update(['delete_time'=>time()]);
    
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }

    public function users()
    {
        $rejects = Db::name('template_reject_reason')->where('type', 1)->order('sort desc,id asc')->select();
        $this->assign('rejects', json_encode($rejects, JSON_UNESCAPED_UNICODE));

        $current_id = Db::name('act_pageants_config')
            ->where(['delete_time' => 0])
            ->where('enroll_time', '<= time', time())
            ->where('end_time', '>= time', time())
            ->value('id');
        $this->assign('current_id', $current_id);
        
        $configs = Db::name('act_pageants_config')
            ->where(['delete_time'=>0])
            ->order('id desc')
            ->column('*', 'id');
        $this->assign('configs', $configs);

        $config_id = input('config_id/d', $current_id ?: 0);
        $this->assign('config_id', $config_id);

        $where = ['delete_time'=>0];
        if ($config_id) {
            $where['config_id'] = $config_id;
        }
        $search_name = input('param.search_name');
        if ($search_name) {
            $where['user_id'] = $search_name;
        }

        $orderidx = input('order/d');
        $order = 'id desc';
        if ($orderidx) {
            switch ($orderidx) {
                case 1:
                    $order = 'create_time asc';
                    break;
                case 2:
                    $order = 'create_time desc';
                    break;
                case 3:
                    $order = 'scoring_count desc';
                    break;
                
                default:
                    break;
            }
        }

        $data = Db::name('act_pageants_user')
                    ->where($where)
                    ->order($order)
                    ->paginate(_getCachePages(), false, ['query' => request()->param()])
                    ->each(function($item) use ($configs){
                        $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                        $item['update_time'] = date('Y-m-d H:i:s', $item['update_time']);
                        $item['config_name'] = $configs[$item['config_id']]['name'];
                        return $item;
                    });

        $page = $data->render();
        $this->assign('search_name', $search_name);
        $this->assign('data', $data);
        $this->assign('order', $orderidx);
        $this->assign('page', $page);
        return $this->fetch();
    }

    public function authadd()
    {
        $id = input('id');

        if (request()->isAjax()) {

            $post = input('post.');

            if ($id) {
                $dy = db('act_pageants_user')->where('id', $id)->find();
                $update = ['state' => $post['shenhe'], 'reason' => $post['reason'], 'audit_time' => time()];
                $db = db('act_pageants_user')->where('id', $id)->update($update);

                if ($db) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            } else {
                $data = ["err" => '参数缺失'];
            }
        }
        return $data;
    }
    public function shenheAll()
    {
        if (request()->isAjax()) {
            $post = input('post.');
            $type = input('type');
            if (input('?post.delAll')) {
                $post = $post['delAll'];
                $db = Db::name('act_pageants_user');
                $timenow = time();
                foreach ($post as $k => $v) {
                    if ($type == 'del') {
                        $res = Db::name('act_pageants_user')->where(['id'=>$v])->find();
                        $dbres = $db->where(['id'=>$v])->update(['delete_time'=>$timenow]);
                    } else {
                        $dy = Db::name('act_pageants_user')->where(['id'=>$v])->find();
                        $update = [
                            'state'    =>  $type,
                            'audit_time'=>$timenow
                        ];
                        $res = $db->where('id', $v)->update($update);
                    }
                }
                if ($res) {
                    $data = ['ret' => '操作成功'];
                } else {
                    $data = ['err' => '操作失败'];
                }
            } else {
                $data = ['err' => '操作失败，未选中数据'];
            }
        } else {
            $data = ['err' => '提交类型错误'];
        }
        return $data;
    }


    public function userdel()
    {
        if (request()->isAjax()) {
            $id = input('id');
            if ($id) {
                $db = Db::name('act_pageants_user')->where(['id'=>$id])->update(['delete_time'=>time()]);
    
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }


    public function scoring()
    {
        $configs = Db::name('act_pageants_config')
            ->where(['delete_time'=>0])
            ->order('id desc')
            ->column('*', 'id');
        $this->assign('configs', $configs);

        $config_id = input('config_id/d', 0);
        $this->assign('config_id', $config_id);
        $touser_id = input('touser_id/d', 0);
        $this->assign('touser_id', $touser_id);

        $where = [];
        if ($config_id) {
            $where['config_id'] = $config_id;
        }
        if ($touser_id) {
            $where['touser_id'] = $touser_id;
        }

        $data = Db::name('act_pageants_scoring')
                    ->where($where)
                    ->order('id desc')
                    ->paginate(_getCachePages(), false, ['query' => request()->param()])
                    ->each(function($item) use ($configs){
                        $item['time'] = date('Y-m-d H:i:s', $item['time']);
                        $item['config_name'] = $configs[$item['config_id']]['name'];
                        return $item;
                    });

        $page = $data->render();
        $this->assign('data', $data);
        $this->assign('page', $page);
        return $this->fetch();
    }

}